<?php
/**
 * Created by PhpStorm.
 * User: yuanjie
 * Date: 2017/3/27
 * Time: 下午4:18
 */
use EasyWeChat\Foundation\Application;
class WechatOauthController extends BaseController
{
    public function check(){
        //业务
      /*  $token = Input::get('token');
        $url = Config::get('config.redirect_url').Input::get('url');
        Session::put('url',$url);
        $user_token = UserTokens::getToken($token);
        $user_id = isset($user_token->user_id)?$user_token->user_id:0;
        Session::put('user_id',$user_id);
        $weixin = UserWeiXinAdd::where('user_id',$user_id)->first();
        if(count($weixin) != 0){
            if(strpos($url,'?') !== FALSE){
                $url = $url.'&to_grant=1';
            }else{
                $url = $url.'?to_grant=1';
            }
            header('location:'. $url);
        }else{
            $wx = Config::get('wechat.CHEPIN');
            $options = $wx['OPTION'];

            $app = new Application($options);

            $oauth = $app->oauth;
            return $oauth->redirect();
        }*/
        $token = Input::get('token');
        $temp_url= strtr(Input::get('url'),'|','&');
        $url = Config::get('config.redirect_url').$temp_url;
        Session::put('url',$url);
        $user_token = UserTokens::getToken($token);
        $user_id = isset($user_token->user_id)?$user_token->user_id:0;
        Session::put('user_id',$user_id);
        $wx = Config::get('wechat.CHEPIN');
        $options = $wx['OPTION'];
        $app = new Application($options);
        $oauth = $app->oauth;
        Log::info('check',array('system'=>"wechat2.0",'CHEPIN' => $wx,'user_token' => $user_token,'original' => $oauth));
        return $oauth->redirect();
    }

    public function callBack(){
        try{
            $wx = Config::get('wechat.CHEPIN');
            $options = $wx['OPTION'];

            $app = new Application($options);
            $oauth = $app->oauth;

//        Log::info('aouth',array('aouth' =>$oauth ));
            $user = $oauth->user();

            //存库
            $user_id = Session::get('user_id');
            if(!empty($user_id)) {
                $users = Users::where('id', $user_id)->first();
                if ($users->openid !== $user->getId()){
                    Users::where('id', $user_id)->update(['openid' => $user->getId()]);
                    $user_weixin_count = UserWeiXinAdd::where('user_id', $user_id)->count();
                    $original = $user->getOriginal();
                    if ($user_weixin_count == 0) {
                        $user_weixin = new UserWeiXinAdd();
                        $user_weixin->user_id = $user_id;
                        $user_weixin->nick_name = $user->getNickname();
                        $user_weixin->sex = $original['sex'];
                        $user_weixin->avatar = $user->getAvatar();
                        $user_weixin->city = $original['city'];
                        $user_weixin->country = $original['country'];
                        $user_weixin->province = $original['province'];
                        $user_weixin->language = $original['language'];
                        $user_weixin->save();
                    }else {
                        $user_weixin = UserWeiXinAdd::find($user_id);
                        $user_weixin->user_id = $user_id;
                        $user_weixin->nick_name = $user->getNickname();
                        $user_weixin->sex = $original['sex'];
                        $user_weixin->avatar = $user->getAvatar();
                        $user_weixin->city = $original['city'];
                        $user_weixin->country = $original['country'];
                        $user_weixin->province = $original['province'];
                        $user_weixin->language = $original['language'];
                        $user_weixin->save();
                    }
                }
            }

            Log::info('oauth',array('system'=>"wechat2.0",'open_id' => $user->getId(),'name' => $user->getNickname(),'original' => $user->getOriginal()));

        }catch (Exception $e){
            $response = array('code' => -1, 'msg' => '失败');
            Log::info("oauth", array("system" => "wechat2.0" ,"event" => "login", 'input' =>Input::all() ,"output" => $response));
        }
        //业务处理
        $targetUrl = Session::get('url');
        $targetUrl = str_replace("is_empower=0","is_empower=1",$targetUrl);
        header('location:'. $targetUrl);
    }
    public function checkPower(){
        $validator = Validator::make(Input::all(),
            array(
                'phone' => 'required',
            )
        );
        do{
            if ($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $openid = Users::where('phone',Input::get('phone'))->pluck('openid');
            if(!empty($openid)){
                $to_grant=1;
            }else{
                $to_grant=2;
            }
            $response = array(
                "code" => 0,
                "msg" => "ok",
                "result" => array(
                    "to_grant" => $to_grant,
                )
            );
        }while(false);
        Log::info("info", array("system" => "wechat2.0" ,"event" => "login", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:
     * @DateTime:    2017-04-06 11:43:32
     * @Description: 微信消息推送
     */
    public static function sendMessage($openid,$templateId,$data,$url){
        $wx = Config::get('wechat.CHEPIN');
        $options = $wx['OPTION'];

        $app = new Application($options);
        $notice = $app->notice;
        $result = $notice->to($openid)->uses($templateId)->withUrl($url)->andData($data)->send();
        return $result;
    }

    /**
     * @Author:      dx
     * @DateTime:    2017-04-05 16:43:32
     * @Description: 微信分享获取前置js sdk
     */
    public function jssdk(){
        do{
            $wx = Config::get('wechat.CHEPIN');
            $options = $wx['OPTION'];

            $app = new Application($options);
            $js = $app->js;
            $APIs = array('onMenuShareQQ', 'onMenuShareWeibo','onMenuShareTimeline','onMenuShareAppMessage');
            $js->setUrl(Input::get('url'));
            $res = $js->config($APIs,$debug = true,$beta = false, $json = true);

            $response = array(
                "code" => 0,
                "msg" => "ok",
                "result" => $res,
            );
        }while(false);
        Log::info("info", array("system" => "wechat2.0" ,"event" => "jssdk", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

}